/**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */

import UIKit

class LSStatusViewModel: NSObject {
    
    //提供微博数据模型
    var status: LSStatus?
    
    //转发数内容
    var retweetCountContent: String?
    //评论数内容
    var commentCountContent: String?
    //赞数内容
    var unlikeCountContent: String?
    //转发微博内容
    var retweetContent: String?
    //来源数据
    var sourceContent: String?
    
    //会员等级图片
    var mbrankImage: UIImage?
    //认证类型图片
    var verifiedTypeImage: UIImage?
    
    var timeContent: String? {
        
        //判断发微博时间是否为nil
        guard let createDateStr = status?.created_at else {
            return nil
        }
        
        return NSDate.sinaDate(createDateStr).sinaDateString
    }
    
    //原创微博富文本
    var origianlAttributedString: NSAttributedString?
    //转发微博富文本
    var retweetAttributedString: NSAttributedString?
    
    //MARK: - 通过重载构造函数初始化当前对象
    init(status: LSStatus) {
        super.init()
        self.status = status
        
        //处理转发,评论,赞的逻辑处理
        retweetCountContent = handleCount(status.reposts_count, defaultTitle: "转发")
        commentCountContent = handleCount(status.comments_count, defaultTitle: "评论")
        unlikeCountContent = handleCount(status.attitudes_count, defaultTitle: "赞")
        
        //处理转发微博
        handleRetweetContent(status)
        //处理来源数据
        handleSource(status.source ?? "")
        //处理会员等级图片
        handleMbrankImage(status.user?.mbrank ?? 0)
        //处理认证类型等级图片
        handleVerifiedTypeImage(status.user?.verified_type ?? -1)
        //处理微博首页的表情描述富文本
        origianlAttributedString = handleEmoticonContentWithStatus(status.text!)
    }
    
    //MARK: - 处理微博数据里面的逻辑
    private func handleEmoticonContentWithStatus(status: String) -> NSAttributedString {
        let result = NSMutableAttributedString(string: status)
        
        var matchResultArray = [LSMatchResult]()
        (status as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (matchCount, matchString, matchRange, _) -> Void in
            
            if let chs = matchString.memory as? String {
                let matchResult = LSMatchResult(matchString: chs, matchRange: matchRange.memory)
                matchResultArray.append(matchResult)
            }
            
        }
        
        //reverse 数组翻转
        for value in matchResultArray.reverse() {
            
            //查找本地的表情模型
            if let emoticon = LSEmoticonTools.sharedTools.searchEmoticonWithChs(value.matchString) {
                print(status)
                //把表情模型转成表情富文本
                //获取取到表情模型里面的图片路径,创建UIImage对象,然后转成富文本
                //通过表情模型和字体对象创建表情富文本
                let attributedStr = NSAttributedString.attributedStringWithEmoticon(emoticon, font: UIFont.systemFontOfSize(StatusFontSize))
                //通过匹配的表情描述的范围替换指定表情富文本
                result.replaceCharactersInRange(value.matchRange, withAttributedString: attributedStr)
                
            }
        }
        return result
    }
    
    //MARK: - 处理转发微博的拼接逻辑
    private func handleRetweetContent(status: LSStatus) {
        
        //判断是否有转发微博内容
        if status.retweeted_status != nil {
            
            //取到内容
            guard let text = status.retweeted_status?.text, let name = status.retweeted_status?.user?.screen_name else {
                return
            }
            //拼接转发微博内容
            let result = "@\(name): \(text)"
            retweetContent = result
            
            //设置转发微博富文本
            retweetAttributedString = handleEmoticonContentWithStatus(retweetContent!)
        }
    }
    
    //MARK: - 处理微博数据里面的逻辑
    
    //MARK: - 处理认证类型等级图片
    private func handleVerifiedTypeImage(verifiedType: Int) {
        //认证类型等级 -1 没有认证 ，0 认证用户，2，3，5 企业认证 ， 220 达人
        switch verifiedType {
        case 0:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImage = nil
            
        }
        
    }
    
    //MARK: - 处理会员等级图片
    private func handleMbrankImage(mbrank: Int) {
        
        if mbrank >= 1 && mbrank <= 6 {
            
            //合法会员等级范围
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        
    }
    
    //MARK: - 处理来源数据
    private func handleSource(source: String) {
        
        //判断字符串中是否包含这样的关键字符串
        if source.containsString("\">") && source.containsString("</") {
            //开始光标位置
            let startIndex = source.rangeOfString("\">")!.endIndex
            //结束光标位置
            let endIndex = source.rangeOfString("</")!.startIndex
            //获取指定范围字符串
            let result = source.substringWithRange(startIndex..<endIndex)
            //设置该来源数据
            sourceContent = "来自: " + result
        }
        
    }
    
    //MARK: - 处理转发,评论,赞数的逻辑
    private func handleCount(count: Int, defaultTitle: String) -> String {
        //判断传入的参数是否大于0
        //不大与0
        //显示原始文本
        if count > 0 {
            
            if count >= 10000 {
                
                let result = CGFloat(count / 1000) / 10
                
                var resultStr = "\(result)万"
                //判断字符串中是否包含0
                if resultStr.containsString(".0") {
                    
                    resultStr = resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
                }
                return resultStr
                
            } else {
                return "\(count)"
            }
            
        } else {
            
            return defaultTitle
        }
    }
}








